package cn.zzf.controller;

import cn.zzf.core.ClassroomHandler;
import cn.zzf.core.ClassroomWriteToDb;
import cn.zzf.core.ContentCrawer;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author GaoFeng2017
 * @date 2018-02-23 10:32:04
 **/

public class ClassroomCrawer {
    private Logger logger = LogManager.getLogger(this.getClass());
    private int count;

    /*http://218.65.5.214:2001/jwweb/ZNPK/Private/List_ROOM.aspx?w=150&id=1*/
    public void doCraw() {
        ContentCrawer crawer = new ContentCrawer.ContentCrawerBuilder()
                .setEncode("utf-8")
                .setUseEntityUtils(true)
                .build();

        String[] cid = {"1","3"};

        for (int i = 0;i < cid.length;i++) {
            ClassroomHandler classroomHandler = new ClassroomHandler();
            crawer.setUrl("http://218.65.5.214:2001/jwweb/ZNPK/Private/List_JXL.aspx");
            crawer.setParamMap(this.createParamMap(cid[i]));
            boolean b = crawer.execute(classroomHandler,"parent.theJXL.innerHTML","");
            List<String> items = classroomHandler.getItems();

            if (b) {
                logger.info(items + "已记录");
            }

            List<String> subItems = null;
            for (int j = 0;j < items.size();j++) {
                classroomHandler = new ClassroomHandler();
                crawer.setUrl("http://218.65.5.214:2001/jwweb/ZNPK/Private/List_ROOM.aspx");
                crawer.setParamMap(createParamMap(String.valueOf(Integer.parseInt(cid[i])*100 + j + 1)));
                boolean sb = crawer.execute(classroomHandler,"parent.theROOM.innerHTML","");
                subItems = classroomHandler.getItems();
                ClassroomWriteToDb classroomWriteToDb = new ClassroomWriteToDb(items.get(j),Byte.valueOf(i + ""),subItems);
                classroomWriteToDb.writeAll();
                count += subItems.size();
                if (sb) {
                    logger.info(subItems + "已记录");
                }
            }

            System.out.println(count);
        }

    }

    public Map<String, String> createParamMap(String id) {
        Map<String,String> map = new HashMap<>(2);
        map.put("w", "150");
        map.put("id", id);
        return map;
    }

    public static void main(String[] args) {
        new ClassroomCrawer().doCraw();
    }
}
